<template>
  <div class="repairTask">
    <MetaSearchForm @on-search="tableSearch">
      <el-form ref="repairTask_form" :model="searchData" label-width="80px" class="repairTask_searchFrom">
        <el-form-item label="设备名称" class="repairTask_searchFromItem">
          <el-input v-model="searchData.equipmentName" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item label="指派时间" class="repairTask_searchFromItem">
          <el-date-picker
            v-model="searchData.dateBetween"
            type="daterange"
            range-separator="-"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="维修状态" class="repairTask_searchFromItem">
          <el-select v-model="searchData.repairStatus" placeholder="请选择维修状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="未完成" value="0"></el-option>
            <el-option label="已完成" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-row style="float:left">
          <el-col :span="8">
            <el-form-item label="省" class="repairTask_searchFromItem">
              <el-select v-model="searchData.province" placeholder="请选择省" @change="provinceHandleChange" clearable>
                <el-option
                  v-for="item in provinceList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="市" class="repairTask_searchFromItem">
              <el-select v-model="searchData.city" placeholder="请选择市" @change="cityHandleChange" clearable>
                <el-option
                  v-for="item in cityList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区" class="repairTask_searchFromItem">
              <el-select v-model="searchData.areaid" placeholder="请选择区" clearable>
                <el-option
                  v-for="item in areaList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </MetaSearchForm>
    <MetaPageTable
      ref="repairTaskTable"
      class="repairTask_table"
      table-title="维修任务单"
      :is-auto-req="true"
      :req-url="reqUrl"
      :req-data="searchDataForTable"
      req-method="post"
      :display-item="displayItem"
      :line-btn-group="lineBtnGroup"
      :lineBtnNum="4"
      @lineBtnClick="tableInlineBtnClick"
    />
    <el-dialog
      v-if="repairSubmitFlag"
      title="维修提报"
      :visible.sync="repairSubmitFlag"
      width="60%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="repairSubmit_form" :model="repairSubmitItem" label-width="110px" :rules="repairSubmitRules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="任务单号">{{repairInfoItem.num}}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备名称">{{repairInfoItem.equipmentName}}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备所在地">{{repairInfoItem.address}}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="报警等级">
              <span v-if="repairInfoItem.warningLevel == '01'" style="color: red">一级</span>
              <span v-else-if="repairInfoItem.warningLevel == '02'" style="color: #8A2BE2">二级</span>
              <span v-else-if="repairInfoItem.warningLevel == '03'" style="color: orange">三级</span>
              <span v-else-if="repairInfoItem.warningLevel == '04'" style="color: blue">四级</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报警类型">{{repairInfoItem.warningType}}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报警时间">{{repairInfoItem.warningTime}}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="报警说明">{{repairInfoItem.warning_content}}</el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="阶段维修成果" prop="content">
          <el-input v-model="repairSubmitItem.content" placeholder="请输入维修成果"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialogFooter">
        <el-button size="mini" @click="closeRepairSubmitDialog()">取消</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="repairSubmit()"
        >提交</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-if="repairToOthersDialogFlag"
      title="维修任务下发"
      :visible.sync="repairToOthersDialogFlag"
      width="50%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="repairTransfer_form" :model="repairToOthersItem" label-width="110px" :rules="repairToRules">
        <el-form-item label="转移给" prop="userId">
          <el-cascader
            v-model="repairToOthersItem.userId"
            :options="orgPersonList"
            :props="{ expandTrigger: 'hover' }">
          </el-cascader>
        </el-form-item>
      </el-form>
      <div class="dialogFooter">
        <el-button size="mini" @click="closeRepairToDialog()">取消</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="repairToOthersSubmit()"
        >保存</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-if="repairRecordDialogFlag"
      title="维修记录"
      :visible.sync="repairRecordDialogFlag"
      width="60%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <div class="repairRecordDialogBg">
        <el-steps direction="vertical" :active="repairRecordData.length - 1" :space="100" finish-status="process" process-status="success">
          <el-step v-for="item in repairRecordData" :key="item.id" :title="item.repairStep == '2' ? '维修提报：' + item.repairLog : item.repairLog" :description="'操作人：' + item.name + ' （ ' + item.createDate + ' ）'"></el-step>
        </el-steps>
      </div>
      <div class="dialogFooter">
        <el-button size="mini" @click="closeRepairRecordDialog()">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import MetaPageTable from '../components/MetaPageTable'
import MetaSearchForm from '../components/MetaSearchForm'
import deepClone from '../utils/deepClone'
export default {
  name: 'repairTask',
  components: {
    MetaPageTable,
    MetaSearchForm
  },
  data () {
    var checkResult = (rule, value, callback) => {
      if (value.trim() === '') {
        return callback(new Error('请填写维修成果'))
      }else{
        return callback()
      }
    }
    return {
      paramOptionDialogFlag: false,
      reqUrl: process.env.PROGOO_GATE_WATER + 'repairInfo/getPage',
      searchData: {
        dateBetween: [],
        province: '',
        city: '',
        areaid: '',
        repairStatus: '0'
      },
      searchDataForTable: {
        repairStatus: ['0', '2', '3'],
        username: localStorage.getItem('username')
      },
      editRules: {
        paramkey: [
          { required: true, message: '请输入参数key', trigger: 'blur' },
        ],
        paramname: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ]
      },
      provinceList: [],
      cityList: [],
      areaList: [],
      displayItem: [
        {
          label: '任务单号',
          prop: 'num'
        },
        {
          label: '设备名称',
          prop: 'equipmentName'
        },
        {
          label: '设备所在地',
          prop: 'address'
        },
        {
          label: '报警等级',
          prop: 'warningLevel',
          type: 'if',
          format: {
            '01': '一级报警',
            '02': '二级报警',
            '03': '三级报警',
            '04': '四级报警'
          },
          color: {
            '01': 'red',
            '02': '#8A2BE2',
            '03': 'orange',
            '04': 'blue'
          }
        },
        {
          label: '报警类型',
          prop: 'warningType'
        },
        {
          label: '报警说明',
          prop: 'warning_content'
        },
        {
          label: '报警时间',
          prop: 'warningTime'
        },
        {
          label: '指派时间',
          prop: 'dispatchTime'
        },
        {
          label: '维修进度',
          prop: 'repairStatus',
        }
      ],
      projectList: [],
      equipmentList: [],
      pointRules: {
        coordinatex: [
          { required: true, message: '请输入坐标x', trigger: 'blur' }
        ],
        coordinatey: [
          { required: true, message: '请输入坐标y', trigger: 'blur' }
        ],
        height: [
          { required: true, message: '请输入高程', trigger: 'blur' }
        ]
      },
      tableStyle: {
        fieldName: 'status',
        fieldValue: '1',
        backgroundColor: '#ffe3e3',
        fontColor: ''
      },
      lineBtnGroup: [
        {
          id: 'start',
          title: '开始',
          hideCheck: this.btnHidecheck
        },
        {
          id: 'submit',
          title: '提报',
          hideCheck: this.btnHidecheck
        },
        {
          id: 'finish',
          title: '结束',
          hideCheck: this.btnHidecheck
        },
        {
          id: 'back',
          title: '任务退回',
          hideCheck: this.btnHidecheck
        },
        {
          id: 'transfer',
          title: '任务下发',
          hideCheck: this.btnHidecheck
        },
        {
          id: 'check',
          title: '维修记录',
          hideCheck: this.btnHidecheck
        }
      ],
      repairSubmitFlag: false,
      repairInfoItem: {},
      repairSubmitItem: {
        content: ''
      },
      repairToOthersItem: {
        userId: []
      },
      repairSubmitRules: {
        content: [
          { required: true, validator: checkResult, trigger: 'blur' },
          { max: 80, message: '长度少于80个字', trigger: 'blur' }
        ]
      },
      repairToRules: {
        userId: [
          { required: true, message: '请选择人员', trigger: 'change' }
        ]
      },
      orgPersonList: [],
      repairToOthersDialogFlag: false,
      repairRecordDialogFlag: false,
      repairRecordData: []
    }
  },
  mounted() {
    this.initPCAList(0, 'province')
    this.getRepairUserData()
  },
  methods: {
    tableInlineBtnClick(item) {
      if (item.button === 'start') {
        let param = {
          "repairId": item.rows.id,//维修单id
          "repairLog": "开始维修",//点击开始  默认log 开始维修
          "repairer": item.rows.repairer,//维修人id
          "repairStep": "1",//维修步骤  开始
          "newRepairer": ""//转移后的维修人 id
        }
        this.$fetch({
          url: process.env.PROGOO_GATE_WATER + "repairInfoDetail/save",
          method: "post",
          data: param
        }).then(res => {
          this.$nextTick(() => {
            this.$refs.repairTaskTable.formDataInit()
          })
        })
      }else if (item.button === 'submit') {
        this.repairSubmitItem = {
          content: ""
        }
        this.repairInfoItem = item.rows

        this.repairSubmitFlag = true
      }else if (item.button === 'finish') {
        this.$confirm("请确认是否已完成维修", "确认完成?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          let param = {
            "repairId": item.rows.id,//维修单id
            "repairLog": "修复完成",
            "repairer": item.rows.repairer,//维修人id
            "repairStep": "4",
            "newRepairer": ""
          }
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "repairInfoDetail/save",
            method: "post",
            data: param
          }).then(res => {
            this.$nextTick(() => {
              this.$refs.repairTaskTable.formDataInit()
            })
          })
        })
      }else if (item.button === 'transfer') { //任务下发
        this.repairInfoItem = item.rows
        for(let i in this.orgPersonList) {
          let has = false
          for(let j in this.orgPersonList[i].children) {
            if(this.orgPersonList[i].children[j].value === this.repairInfoItem.repairer) {
              this.orgPersonList[i].children[j].disabled = 'disabled'
              has = true
              break
            }
          }
          if(has) {
            break
          }
        }
        this.repairToOthersItem = {
          userId: []
        }
        this.repairToOthersDialogFlag = true
      }else if (item.button === 'back') { // 任务退回
        let newRepairer = ''
        for(let i in this.orgPersonList) {
          let leader = ''
          let has = false
          for(let j in this.orgPersonList[i].children) {
            if(this.orgPersonList[i].children[j].value === item.rows.repairer) {
              has = true
            }
            if(this.orgPersonList[i].children[j].isLeader == '1') {
              leader = this.orgPersonList[i].children[j].value
            }
            if(has && leader !== '') {
              break
            }
          }
          if(has && leader !== '') {
            newRepairer = leader
            break
          }
        }
        if(newRepairer == '') {
          this.$notify.warning({
            title: "警告",
            message: "当前部门未设置主管，无法退回。",
          });
          return
        }
        this.$confirm("任务退回需要先联系主管后进行退回，确认是否执行任务退回", "确认退回?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {

          let param = {
            "repairId": item.rows.id,//维修单id
            "repairLog": item.rows.repairer + ',' + newRepairer,
            "repairer": item.rows.repairer,//维修人id
            "repairStep": "5", //任务退回
            "newRepairer": newRepairer
          }
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "repairInfoDetail/save",
            method: "post",
            data: param
          }).then(res => {
            this.$nextTick(() => {
              this.$refs.repairTaskTable.formDataInit()
            })
            this.$notify.success({
              title: "成功",
              message: "退回成功!",
            });
          })
        })

      }else if (item.button === 'check') {
        this.$fetch({
          url: process.env.PROGOO_GATE_WATER + "repairInfoDetail/getList",
          method: "get",
          params: {
            repairId: item.rows.id
          }
        }).then(res => {
          this.repairRecordData = res.data.result
          this.repairRecordDialogFlag = true
        })
      }
    },
    repairSubmit() {
      this.$refs['repairSubmit_form'].validate((valid) => {
        if (valid) {
          let param = {
            "repairId": this.repairInfoItem.id,//维修单id
            "repairLog": this.repairSubmitItem.content,
            "repairer": this.repairInfoItem.repairer,//维修人id
            "repairStep": "2",
            "newRepairer": ""
          }
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "repairInfoDetail/save",
            method: "post",
            data: param
          }).then(res => {
            this.closeRepairSubmitDialog()
            this.$nextTick(() => {
              this.$refs.repairTaskTable.formDataInit()
            })
            this.$notify.success({
              title: "成功",
              message: "提报成功!",
            });
          })
        } else {
          return false;
        }
      })
    },
    closeRepairSubmitDialog() {
      this.repairSubmitItem = {
        content: ''
      }
      this.repairInfoItem = {}
      this.repairSubmitFlag = false
    },
    tableSearch() {
      let param = {}
      for(let key in this.searchData) {
        if(key === 'dateBetween') {
          param.startTime = this.searchData[key] && this.searchData[key].length > 0 ? this.searchData[key][0] + ' 00:00:00' : ''
          param.endTime =  this.searchData[key] && this.searchData[key].length > 0 ? this.searchData[key][1] + ' 23:59:59' : ''
        }else if(key === 'repairStatus') {
          param.repairStatus = ['0','1' , '2', '3']
          if(this.searchData[key] == '0') {
            param.repairStatus = ['0', '2', '3']
          }else if(this.searchData[key] == '1') {
            param.repairStatus = ['1']
          }
        }else {
          param[key] = this.searchData[key]
        }
      }
      param.username = localStorage.getItem('username')
      this.searchDataForTable = param
      this.$nextTick(() => {
        this.$refs.repairTaskTable.formDataInit(true)
      })

    },
    provinceHandleChange(id) {
      this.cityList = []
      this.areaList = []
      this.searchData.city = ''
      this.searchData.areaid = ''
      if(id !== '') {
        this.initPCAList(id, 'city')
      }
    },
    cityHandleChange(id) {
      this.areaList = []
      this.searchData.areaid = ''
      if(id !== '') {
        this.initPCAList(id, 'area')
      }
    },
    initPCAList(id, type, callback) {
      if(id === '') {
        return
      }
      let data = {}
      if(type === 'province') {
        data.level = 1
      }else if (type === 'city') {
        data.level = 2
      }else if (type === 'area') {
        data.level = 3
      }
      data.parentid = id
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/company/area",
        method: "post",
        data: data
      }).then(res => {
        if(type === 'province') {
          this.provinceList = res.data.result
        }else if (type === 'city') {
          this.cityList = res.data.result
        }else if (type === 'area') {
          this.areaList = res.data.result
        }
        if(callback && typeof(callback) === 'function') {
          callback()
        }
      })
    },
    btnHidecheck(rowData, item) {
      if(rowData.repair_status === '3' && item.id === 'start') {
        return true
      }
      if(rowData.repair_status === '2' && (item.id === 'submit' || item.id === 'finish')) {
        return true
      }
      if(rowData.repair_status !== '3' && item.id === 'check') {
        return true
      }
      if(rowData.isLeader === '0' && item.id === 'back') {
        return true
      }
      if(rowData.isLeader === '1' && item.id === 'transfer') {
        return true
      }
      return false
    },
    getRepairUserData(item) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "maintenancePerson/getDeptAndPersonList",
        method: "get",
        params: {},
      }).then((res) => {
        if(res.data.code === 200) {
          this.orgPersonList = []
          for(let i in res.data.result) {
            let orgItem = {}
            orgItem.value = res.data.result[i].deptId
            orgItem.label = res.data.result[i].deptName
            orgItem.children = []
            for(let j in res.data.result[i].list) {
              let personList = {}
              personList.value = res.data.result[i].list[j].userId
              personList.label = res.data.result[i].list[j].name + "(" + res.data.result[i].list[j].username + ")"
              personList.isLeader = res.data.result[i].list[j].isLeader

              // let repairContent = res.data.result[i].list[j].technique.split(',')
              // let has = false
              // for(let rIndex in repairContent) {
              //   if(repairContent[rIndex] === item.remarkKey) {
              //     has = true
              //     break
              //   }
              // }
              // if(!has) {
              //   personList.disabled = 'disabled'
              // }
              orgItem.children.push(personList)
            }
            this.orgPersonList.push(orgItem)
          }
        }else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    closeRepairToDialog() {
      this.repairToOthersItem = {
        userId: []
      }
      this.repairToOthersDialogFlag = false
    },
    repairToOthersSubmit() {
      this.$refs['repairTransfer_form'].validate((valid) => {
        if (valid) {
          let newRepairer = this.repairToOthersItem.userId.length > 1 ? this.repairToOthersItem.userId[1] : ''
          let param = {
            "repairId": this.repairInfoItem.id,//维修单id
            "repairLog": this.repairInfoItem.repairer + ',' + newRepairer,
            "repairer": this.repairInfoItem.repairer,//维修人id
            "repairStep": "3", //任务下发
            "newRepairer": newRepairer
          }
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "repairInfoDetail/save",
            method: "post",
            data: param
          }).then(res => {
            this.closeRepairToDialog()
            this.$nextTick(() => {
              this.$refs.repairTaskTable.formDataInit()
            })
            this.$notify.success({
              title: "成功",
              message: "下发成功!",
            });
          })
        } else {
          return false;
        }
      });
    },
    closeRepairRecordDialog() {
      this.repairRecordDialogFlag = false
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.repairTask{
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px;
  overflow-y: scroll;
  .repairTask_table {
    width: 100%;
    overflow-y: unset;
  }
  .dataDetailsForm_item {
    line-height: normal;
    padding: 8px 0;
  }
  .repairTask_searchFrom {
    width: 100%;
    .repairTask_searchFromItem {
      float: left;
    }
  }
  .repairRecordDialogBg {
    width: 100%;
    max-height: 500px;
    overflow-y: scroll;
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
}
</style>
